<template>
  <a-drawer v-model:visible="visible" :title="modalTitle" :closable="false" :maskClosable="false" width="80%"
    :footer-style="{ textAlign: 'right' }" @close="handleCancel">
    <a-form :model="formState" ref="formRef">
      <a-tabs v-model:activeKey="state.activeKey">
        <a-tab-pane key="1" tab="基础信息" forceRender>
          <a-row type="flex" :gutter="24">
            <a-col :span="12">
              <a-form-item label="商品名称" name="goods_name" :rules="[{ required: true, message: '请输入商品名称' }]">
                <a-input placeholder="请输入商品名称" v-model:value="formState.goods_name" show-count :maxlength="60" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品编号" name="goods_no">
                <a-input placeholder="请输入商品编号" v-model:value="formState.goods_no" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品分类" name="goods_cate" :rules="[{ required: true, message: '请选择分类' }]">
                <a-tree-select v-model:value="formState.goods_cate" style="width: 100%" :tree-data="state.cateList"
                  allow-clear treeDefaultExpandAll show-search :show-checked-strategy="SHOW_ALL" placeholder="请选择分类"
                  multiple treeNodeFilterProp="name" :field-names="{
                    children: 'child',
                    label: 'name',
                    value: 'cate_id',
                  }" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品服务" name="goods_service" :rules="[{ required: true, message: '请选择商品服务' }]">
                <a-select v-model:value="formState.goods_service" mode="multiple" placeholder="请选择商品服务"
                  :options="state.ServiceOptions" :field-names="{ label: 'name', value: 'service_id' }"></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品标签" name="goods_label">
                <a-select v-model:value="formState.goods_label" mode="multiple" placeholder="请选择商品标签"
                  :options="state.LabelOptions" :field-names="{ label: 'name', value: 'label_id' }"></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品类型" name="goods_type">
                <a-radio-group v-model:value="formState.goods_type" :disabled="isEdit">
                  <a-radio :value="1">普通商品</a-radio>
                  <a-radio :value="2">兑换商品</a-radio>
                  <a-radio :value="3">申购商品</a-radio>
                  <a-radio :value="4">特价商品</a-radio>
                  <a-radio :value="5">膨胀商品</a-radio>
                  <a-radio :value="6">申购商品（新）</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="formState.goods_type == 5">
              <a-row type="flex">
                <a-col :span="12">
                  <a-form-item label="总共需要膨胀金额">
                    <a-input-number style="width: 300px" v-model:value="formState.expansion_data.expansion_price" :min="0"
                      placeholder="请输入膨胀金额" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="每日自动膨胀金额">
                    <a-input-number style="width: 300px" v-model:value="formState.expansion_data.day_price" :min="0"
                      placeholder="请输入自动膨胀金额" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="每日签到膨胀金额">
                    <a-input-number style="width: 300px" v-model:value="formState.expansion_data.sign_price" :min="0"
                      placeholder="请输入签到膨胀金额" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="邀请一个下级膨胀金额">
                    <a-input-number style="width: 300px" v-model:value="formState.expansion_data.invite_price" :min="0"
                      placeholder="请输入下级膨胀金额" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col :span="24" v-if="formState.goods_type == 4">
              <a-row type="flex">
                <a-col :span="12">
                  <a-form-item label="最多点赞人数">
                    <a-input-number style="width: 300px" v-model:value="formState.special_data.number" :min="0"
                      placeholder="请输入最多点赞人数" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="每个点赞返现金额">
                    <a-input-number style="width: 300px" v-model:value="formState.special_data.price" :min="0"
                      placeholder="请输入每个点赞返现金额" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="最多下级购买人数">
                    <a-input-number style="width: 300px" v-model:value="formState.special_data.buy_number" :min="0"
                      placeholder="请输入最多下级购买人数" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="每个下级购买返现金额">
                    <a-input-number style="width: 300px" v-model:value="formState.special_data.buy_price" :min="0"
                      placeholder="请输入每个下级购买返现金额" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否运行分销提成" name="is_rebate">
                <a-radio-group v-model:value="formState.is_rebate">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品角标" name="superscript" extra="请在此处输入不能超过4个中文字符">
                <a-input v-model:value="formState.superscript" placeholder="请输入商品角标" maxLength="4" style="width: 300px"
                  allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品角标图片" name="superscript_icon">
                <a-form-item-rest>
                  <app-upload :fileList="formState.superscript_icon" :min="1" @upload-img="uploadSuperscript" />
                </a-form-item-rest>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品边框图片">
                <a-form-item-rest>
                  <app-upload :fileList="formState.img_frame" :min="1" @upload-img="uploadFrame" />
                </a-form-item-rest>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="商品赠送" v-if="formState.goods_give">
                <a-space>
                  <a-form-item label="" extra="积分">
                    <a-input placeholder="积分" v-model:value="formState.goods_give.bonus"></a-input>
                  </a-form-item>
                  <a-form-item label="" extra="红包">
                    <a-input placeholder="红包" v-model:value="formState.goods_give.red"></a-input>
                  </a-form-item>
                  <a-form-item label="" extra="能量">
                    <a-input placeholder="能量" v-model:value="formState.goods_give.energy"></a-input>
                  </a-form-item>
                  <a-form-item label="" extra="最大红包">
                    <a-input placeholder="最大红包" v-model:value="formState.goods_give.max_red"></a-input>
                  </a-form-item>
                  <a-form-item label="" extra="是否可使用红包">
                    <a-switch v-model:checked="formState.goods_give.is_red" checked-children="是" :checkedValue="1"
                      un-checked-children="否" :unCheckedValue="0" />
                  </a-form-item>
                </a-space>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品排序" name="sort" extra="排序从大到小">
                <a-input-number style="width: 200px" v-model:value="formState.sort" placeholder="请输入排序" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="虚拟销量" name="goods_unsales">
                <a-input-number style="width: 200px" v-model:value="formState.goods_unsales" :min="0"
                  placeholder="请输入虚拟销量" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="每人限购数量" name="limit_num" extra="0就是不限购,大于0就限购">
                <a-input-number style="width: 200px" v-model:value="formState.limit_num" :min="0" placeholder="请输入限购数量" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否允许自提" name="shop_type">
                <a-radio-group v-model:value="formState.shop_type">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12" v-if="formState.shop_type == 1">
              <a-form-item label="商品店铺" name="goods_shop" :rules="[
                {
                  required: true,
                  message: '请选择商品店铺',
                },
              ]">
                <a-select v-model:value="formState.goods_shop" placeholder="请选择商品店铺" :options="state.ShopOptions"
                  mode="multiple" allowClear :field-names="{ label: 'shop_name', value: 'shop_id' }"></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否虚拟商品1" name="is_virtually">
                <a-radio-group v-model:value="formState.is_virtually" :disabled="isEdit">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="供应商信息" name="supplier_info">
                <a-input placeholder="例如张三  13888888888" v-model:value="formState.supplier_info"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="商品图片" name="slider_image" :rules="[{ required: true, message: '请选择商品图片' }]"
            extra="*第一张图片默认为商品主图，上传的主图需要为正方形，建议尺寸为800*800px，大小在3M以内。">
            <a-form-item-rest>
              <app-upload :fileList="formState.slider_image" :min="5" @upload-img="uploadImg" :isDragg="true" />
            </a-form-item-rest>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="2" tab="商品规格" forceRender>
          <a-form-item label="商品规格" :rules="[{ required: true, message: '请输入商品规格' }]" style="width: 100%">
            <a-button type="primary" @click="addTable" class="flex items-center">
              <template #icon>
                <PlusOutlined />
              </template>
              添加商品规格
            </a-button>
            <div class="mt-2">
              <SkuTable :dataSource="formState.goods_sku" @delete-img="delSkuImg" @select-img="selectSkuImg"
                @delete-sku="delGoodsSku" @expend-price="handleExpend" />
            </div>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="3" tab="商品参数" forceRender>
          <a-form-item label="商品参数">
            <a-button type="primary" @click="addGoodsParams" class="flex items-center">
              <template #icon>
                <PlusOutlined />
              </template>
              添加商品参数
            </a-button>
            <div class="mt-3">
              <ParamsTable :dataSource="formState.goods_params" @delete="handleDelParams" />
            </div>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="4" tab="商品简介" forceRender>
          <a-form-item label="商品简介">
            <Editor :content="formState.goods_brief" @getContent="getGoodsBrief"></Editor>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="5" tab="详情介绍" forceRender>
          <a-form-item label="详情介绍" :rules="[{ required: true, message: '请输入详情介绍' }]">
            <Editor :content="formState.content" @getContent="getContent" :eheight="800"></Editor>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
    <template #footer>
      <a-button style="margin-right: 8px" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-drawer>
  <!--选择sku图片-->
  <app-img-drawer ref="imgRef" @drawer-success="appImg" />
</template>
<script setup>
import useModal from "@/utils/useModal";
import { reactive, ref, watch } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message, TreeSelect } from "ant-design-vue";
import { treeCate as getCateList } from "@/api/goods/cate";
import { info, add, edit } from "@/api/goods/goods";
import { all as getAllLabel } from "@/api/goods/label";
import { all as getAllService } from "@/api/goods/service";
import { all as getAllNewer } from "@/api/goods/newer";
import { getShop } from "@/api/home";

const { visible, modalTitle } = useModal();

const emits = defineEmits(["model-success"]);
const SHOW_ALL = TreeSelect.SHOW_ALL;

const formRef = ref();
const imgRef = ref();

const formState = reactive({
  goods_name: "",
  goods_cate: [],
  goods_service: [],
  goods_label: [],
  new_type: 0,
  newer_id: null, // 新人活动
  is_rebate: null,
  shop_type: 0, //是否允许自提
  is_virtually: 0, //是否虚拟商品
  goods_type: null, //商品类型
  content: "",
  slider_image: [],
  img_frame: [],
  superscript_icon: [
    {
      url: 'https://chuangfu-shop.oss-cn-chengdu.aliyuncs.com/image/20231101/1ce652da6b8340054c6b4b98a47e11d7.png'
    }
  ],
  sort: 0,
  goods_no: "",
  goods_unsales: 0,
  limit_num: 0,
  expansion_data: {
    expansion_price: "",
    day_price: "",
    sign_price: "",
    invite_price: "",
  }, //膨胀金商品
  goods_give: {
    bonus: null,
    red: null,
    energy: null,
    max_red: null,
    is_red: 0,
  },
  goods_params: [],
  goods_sku: [],
  goods_brief: "",
  goods_shop: [], //商品店铺
  special_data: {
    number: null,
    price: null,
    buy_number: null,
    buy_price: null,
  }, //特价商品,
  superscript: "京东自营",
  supplier_info: "", //供应商信息
});
const state = reactive({
  cateList: [], //分类列表
  activeKey: "1", //tab切换的
  skuIndex: 0, //选择sku的图片
  LabelOptions: [],
  NewerOptions: [],
  ServiceOptions: [],
  ShopOptions: [],
});
const isEdit = ref(false); //是否编辑

const show = (model) => {
  console.log('model===',model)
  modalTitle.value = model ? "编辑商品" : "新增商品";
  state.activeKey = "1";
  getAllNewerList();
  getAllCateList();
  getAllLabelList();
  getAllServiceList();
  getShopList();
  visible.value = true;
  if (model) {
    //编辑
    isEdit.value = true;
    getDetails(model.goods_id);
  } else {
    formState.content=''//清空富文本
    isEdit.value = false;
    resetForm(model);
  }
};
// 根据膨胀金自动计算功能
watch(() => formState.expansion_data.expansion_price, val => {

  if (val > 0) {
    let amount = (val / 40).toFixed(2)
    formState.expansion_data.invite_price = ((amount * (1 / 3)) / 2).toFixed(2)
    formState.expansion_data.day_price = (amount * (2 / 3)).toFixed(2)
    formState.expansion_data.sign_price = (amount * (1 / 3)).toFixed(2)
  }
  if (val <= 0) {
    formState.expansion_data.day_price = ""
    formState.expansion_data.sign_price = ""
    formState.expansion_data.invite_price = ""
  }
})
const getAllLabelList = () => {
  getAllLabel().then((res) => {
    if (res.code == 0) state.LabelOptions = res.data;
  });
};
const getAllServiceList = () => {
  getAllService().then((res) => {
    if (res.code == 0) state.ServiceOptions = res.data;
  });
};
// 获取店铺列表
const getShopList = () => {
  getShop().then((res) => {
    if (res.code == 0) state.ShopOptions = res.data.data || [];
  });
};
// 获取所有新人活动
const getAllNewerList = () => {
  getAllNewer().then((res) => {
    if (res.code == 0) state.NewerOptions = res.data || [];
  });
};
const addGoodsParams = () => {
  const newData = {
    title: "",
    content: "",
  };
  formState.goods_params = [...formState.goods_params, newData];
};
const handleDelParams = (index) => {
  formState.goods_params.splice(index, 1);
};
//选择规格的图片
const selectSkuImg = (index) => {
  state.skuIndex = index;
  imgRef.value.show();
};
const addTable = () => {
  const newData = {
    sku_name: "",
    goods_price: "",
    cost_price: "",
    market_price: "",
    stock_num: "",
    sku_img: "",
  };
  formState.goods_sku = [...formState.goods_sku, newData];
};
const uploadImg = (item) => {
  formState.slider_image = formState.slider_image.concat(item);
};
const uploadSuperscript = (item) => {
  formState.superscript_icon = formState.superscript_icon.concat(item);
}
const uploadFrame=(item)=>{
  formState.img_frame = formState.img_frame.concat(item);
}
const delGoodsSku = (index) => {
  formState.goods_sku.splice(index, 1);
};
const handleExpend = (e) => {
  formState.expansion_data.expansion_price = e
}
const delSkuImg = (index) => {
  formState.goods_sku[index].sku_img = "";
};
const getGoodsBrief = (values) => {
  formState.goods_brief = values;
};
const getContent = (values) => {
  formState.content = values;
};
const appImg = (val) => {
  formState.goods_sku[state.skuIndex].sku_img = val[0];
};
//获取分类
const getAllCateList = () => {
  getCateList().then(function (res) {
    if (res.code == 0) {
      const data = res.data;
      state.cateList = data.map((item) => {
        return {
          ...item,
          disabled: item.status == 0 ? true : false,
          children:
            item.child?.map((ele) => {
              return {
                ...ele,
                disabled: ele.status == 0 ? true : false,
              };
            }) || [],
        };
      });
    }
  });
};
const getDetails = (goods_id) => {
  info({ id: goods_id }).then(function (res) {
    if (res.code == 0) {
      const data = res.data;
      resetForm(data);
      formState.content = data.content;
      if (formState.expansion_data == null) {
        formState.expansion_data = {
          expansion_price: 0
        }
      }
      formState.slider_image =
        data.slider_image?.map((ele) => {
          return {
            url: ele,
          };
        }) || [];

      formState.img_frame = formState.img_frame
          ? [
            {
              url: formState.img_frame,
            },
          ]
          : [];

      formState.superscript_icon = formState.superscript_icon
        ? [
          {
            url: formState.superscript_icon,
          },
        ]
        : [];

      if (formState.goods_sku.length > 0 && formState.goods_sku[0].market_price !== formState.goods_sku[0].goods_price) {
        formState.expansion_data.expansion_price = (formState.goods_sku[0].market_price - formState.goods_sku[0].goods_price).toFixed(2)
      }


      if (formState.goods_give == null) {
        formState.goods_give = {
          bonus: null,
          red: null,
          energy: null,
          max_red: null,
          is_red: 0,
        };
      }



    }
  });
};
//设置表单的值
const resetForm = function (values) {
  for (var i in values) {
    formState[i] = values[i];
  }
};
// 保存
const handleOk = async () => {
  await formRef.value.validate().then(() => {
    const params = {
      ...formState,
      slider_image: formState.slider_image?.map((item) => item.url),
      superscript_icon: formState.superscript_icon.length > 0 ? formState.superscript_icon[0]?.url : "",
      img_frame: formState.img_frame.length > 0 ? formState.img_frame[0]?.url : "",
    };
    if (formState.goods_id) {
      edit({
        id: formState.goods_id,
        ...params,
      }).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          handleCancel();
          emits("model-success");
        }
      });
    } else {
      //添加
      add(params).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          handleCancel();
          emits("model-success");
        }
      });
    }
  });
};
const handleCancel = () => {
  formRef.value.resetFields();
  visible.value = false;
};
defineExpose({
  show,
});
</script>